﻿using HouseOfMystery.Filters;
using HouseOfMystery.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace HouseOfMystery.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        HouseDb db = new HouseDb();
        string currentId = WebSecurity.CurrentUserId.ToString();

        public ActionResult Index()
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

            return View(state);
        }

        public void CollectFirstKey()
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);
            state.Items.ElementAtOrDefault(1).Name = "roomkey_1";

            db.SaveChanges();
        }

        public void SelectItem(int Id)
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

            if (GlobalVars.SelectedItem == state.Items.ElementAtOrDefault(Id).Name)
            {
                // deselect item
                GlobalVars.SelectedItem = null;
            }
            else if (state.Items.ElementAtOrDefault(Id).Name != null)
            {
                GlobalVars.SelectedItem = state.Items.ElementAtOrDefault(Id).Name;
            }
        }

        public string GetItemName(int Id)
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

            if (state.Items.ElementAtOrDefault(Id).Name != null)
            {
                return state.Items.ElementAtOrDefault(Id).Name;
            }

            return null;
        }

        public string GetItemsNames()
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);
            string[] names = new string[10];

            for (int i = 1; i <= 9; i++)
            {
                if (state.Items.ElementAtOrDefault(i).Name != null)
                {
                    names[i] = state.Items.ElementAtOrDefault(i).Name;
                }
            }

            string result = String.Join(",", names);

            return result;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
